//
//  ZXY_NetOperation.m
//  PeckDeclareProjection
//
//  Created by 宇周 on 15/10/21.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_NetOperation.h"
#import <AFNetworking/AFNetworking.h>
#define PRIMARYKEY @"Duostec"
@interface ZXY_NetOperation(NetWorkCode)
- (NSString *)parameterToJsonString:(id)parameter;
- (NSString *)base64StringWithString:(NSString *)inputString;
- (NSString *)stringWithBase64String:(NSString *)baseString;
- (NSString *)md5StringToJsonString:(NSString *)jsonString
                      withPreString:(NSString *)preString
                       andTimeStack:(NSString *)timeStack;
- (NSString *)decodeMd5String:(NSString *)decodeString
                withPreString:(NSString *)preString
                 andTimeStack:(NSString *)timeStack;

- (NSDictionary *)toValidateParameter:(NSDictionary *)parameter
                         andPreString:(NSString *)preString;
@end

#pragma mark -
#pragma mark ------------ 数据加密解密 ------------
@implementation ZXY_NetOperation (NetWorkCode)


/**
 *  将NSDictionary 或者 NSArray转换为json 字符串
 *
 *  @param parameter 需要转换的对象
 *
 *  @return 返回json字符串
 */
- (NSString *)parameterToJsonString:(id)parameter
{
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:parameter
                                   options:NSJSONWritingPrettyPrinted
                                     error:nil]; //转换成jsonData
    //将jsonData转换为jsonString
    NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                 encoding:NSUTF8StringEncoding];
    return jsonString;
}


- (id)stringToJsonObject:(NSString *)jsonString
{
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return jsonObject;
}


/**
 *  将字符串转换为base64
 *
 *  @param inputString 需要转换的字符串
 *
 *  @return 转换之后的base64 字符串
 */
- (NSString *)base64StringWithString:(NSString *)inputString
{
    NSData *jsonData = [inputString dataUsingEncoding:NSUTF8StringEncoding];//将字符串转换为NSData类型，编码方式为UTF－8
    NSString *baseString = [jsonData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];//base64编码
    return baseString;
}

/**
 *  将base64String 解码
 *
 *  @param baseString 需要解码的字符串
 *
 *  @return 转码之后的字符串 转码失败返回nil
 */
- (NSString *)stringWithBase64String:(NSString *)baseString
{
    NSData *baseData = [[NSData alloc] initWithBase64EncodedString:baseString
                                                           options:NSDataBase64DecodingIgnoreUnknownCharacters];//将编码后的base64字符串转解码成data
    
    if(baseData == nil)/* 如果为空表示解码失败，需要返回空 */
    {
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:baseData encoding:NSUTF8StringEncoding];//获取解码后的字符串
    return jsonString;
}

/**
 *  数据加密，（pre ＋ timeStack）.sub(-10) ＋ jsonString.base
 *
 *  @param jsonString 真实数据的json字符串
 *  @param preString  前缀 暂定为：Duostec
 *  @param timeStack  时间戳
 *
 *  @return 返回加密后的数据
 */
- (NSString *)md5StringToJsonString:(NSString *)jsonString
                      withPreString:(NSString *)preString
                       andTimeStack:(NSString *)timeStack
{
    NSString *preStringWithTimeStack = [NSString stringWithFormat:@"%@%@",preString , timeStack];//合成（prestring + timeStack）
    NSString *md5Pre = [preStringWithTimeStack md5];//对合成的字符串进行md5加密
    NSString *realPre = [md5Pre substringFromIndex:md5Pre.length - 10];//加密后取出后十位
    NSString *jsonStringBase64       = [self base64StringWithString:jsonString]; //数据部分需要编码为base64
    NSString *returnString           = [NSString stringWithFormat:@"%@%@",realPre , jsonStringBase64];//组合
    return returnString;
}

/**
 *  解析获取json字符串
 *
 *  @param decodeString 经过md5.base64编码的字符串
 *  @param preString    前缀 默认：Duostec
 *  @param timeStack    时间戳
 *
 *  @return 返回解码之后的数据字符串
 */
- (NSString *)decodeMd5String:(NSString *)decodeString
                withPreString:(NSString *)preString
                 andTimeStack:(NSString *)timeStack
{
    if(decodeString.length <= 10)
    {
        return @"";
    }
    NSString *preStringWithTimeStack = [NSString stringWithFormat:@"%@%@",preString , timeStack];//合成（prestring + timeStack）
    NSString *md5Pre = [preStringWithTimeStack md5];//对合成的字符串进行md5加密
    NSString *realPre = [md5Pre substringFromIndex:md5Pre.length - 10];//加密后取出后十位
    
    /**
     *  与传入的字符串进行比对
     */
    if([realPre isEqualToString:[decodeString substringToIndex:10]])
    {
        //比对成功
        NSString *jsonString = [decodeString substringFromIndex:10];
        return [self stringWithBase64String:jsonString];
    }
    else
    {
        //比对失败
        NSLog(@"解析错误");
        return @"";
    }
}

/**
 *  将明文的网络参数转换为加密
 *
 *  @param parameter 明文网络请求参数
 *  @param preString 加密头部默认 Duostec
 *
 *  @return 返回加密的参数
 */
- (NSDictionary *)toValidateParameter:(NSDictionary *)parameter
                         andPreString:(NSString *)preString
{
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSString *timeStack      = [NSString stringWithFormat:@"%.0lf",interval];
    NSString *encodeParameter = [self md5StringToJsonString:[self parameterToJsonString:parameter] withPreString:preString andTimeStack:timeStack];
    NSDictionary *realPara = @{@"data" : encodeParameter , @"time" : timeStack};
    return realPara;
}
@end

#pragma mark -
#pragma mark ------------ 网络请求 ------------
@implementation ZXY_NetOperation


- (void)postMethod:(NSString *)urlString
      andParameter:(NSDictionary *)parameter
           success:(void (^) (NSDictionary *returnDic)) success
              fail:(void (^) (NSString *errorCoe , NSString *errorMsg))fail
{
    AFHTTPRequestOperationManager *operation = [AFHTTPRequestOperationManager manager];
    [operation setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    NSDictionary *currentParameter ;
    if(parameter == nil)
    {
        currentParameter = [self toValidateParameter:@{} andPreString:PRIMARYKEY];
    }
    else
    {
        currentParameter = [self toValidateParameter:parameter andPreString:PRIMARYKEY];
    }
    [operation POST:urlString parameters:currentParameter success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if(success)
        {
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableLeaves error:nil];
            NSString *data = responseDic[@"data"];
            NSString *resultCode = [NSString stringWithFormat:@"%@",responseDic[@"code"]];
            if(![resultCode isEqualToString:@"1000"])
            {
                NSInteger intCode = resultCode.integerValue;
                if(fail)
                {
                    fail(resultCode , [ZXY_NetHelper errorMessageForCode:intCode]);
                }
            }
            else
            {
                NSNumber *timeNumer = responseDic[@"time"];
                NSString *decodeString = [self decodeMd5String:data withPreString:PRIMARYKEY andTimeStack:timeNumer.stringValue];
                NSMutableDictionary *successDic = [NSMutableDictionary dictionaryWithDictionary:responseDic];
                successDic[@"data"] = [self stringToJsonObject:decodeString];
                success(successDic);

            }
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        if(fail)
        {
            fail(@"404" , @"网络链接错误");
        }
    }];
}
//get方法
- (void)getMethod:(NSString *)urlStr andParaneter:(NSDictionary *)parameter
          success:(void (^) (NSDictionary *returnDic)) success
             fail:(void (^) (NSString *errorCoe , NSString *errorMsg))fail
{
    AFHTTPRequestOperationManager *operation = [AFHTTPRequestOperationManager manager];
    [operation setRequestSerializer:[AFHTTPRequestSerializer serializer]];
    [operation setResponseSerializer:[AFHTTPResponseSerializer serializer]];
    [operation GET:urlStr parameters:parameter success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if(success)
        {
            NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableLeaves error:nil];
            NSString *resultCode = [NSString stringWithFormat:@"%@",responseDic[@"code"]];
            if(![resultCode isEqualToString:@"1000"])
            {
                if(fail)
                {
                    fail(resultCode , @"");
                }
            }
            else
            {
                NSMutableDictionary *successDic = [NSMutableDictionary dictionaryWithDictionary:responseDic];
                success(successDic);
            }
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        if(fail)
        {
            fail(@"404" , @"网络链接错误");
        }
    }];
}
@end

